<template>
	<default-header-page-layout ref="page" title="搬运作业" >
		<view class="page-frame with-action-user-row" :style="{height:pageBodyHeight+'px'}" v-if="pageBodyHeight">
			<action-user-row />
			<view class="with-action-user-row-page-content">
				<easy-select-form-item
					:class="[form.line?'forma-item':'']"
					label="产线"
					v-model="form.line"
					:msg="msg.line"
					:list="selectOptions.lines"
					value-field="id"
					label-field="name"
					:clearable="false"
				/>
				
				<template v-if="form.line">
					<easy-select-form-item
						class="forma-item"
						label="起始位"
						v-model="form.startCode"
						:msg="msg.startCode"
						:list="selectOptions.starts"
						value-field="code"
						label-field="name"
						:clearable="false"
						@select="onSelectStart"
					/>
					
					<view v-if="selectContainer && form.startCode" class="only-watch-container forma-item">
						<view class="label">托盘码：</view>
						<view class="content auto-wrap">{{selectContainer}}</view>
					</view>
					
					<scan-input-form-item
						v-if="!selectContainer && form.startCode"
						class="forma-item"
						label="托盘码"
						v-model="form.container"
						:msg="msg.container"
						:msg-type="msgType.container"
						@search="onSearchContainer"
						@clear="onClearContainer"
					/>
					
					<easy-select-form-item
						label="目标位"
						v-model="form.endCode"
						:msg="msg.endCode"
						:list="selectOptions.ends"
						value-field="code"
						label-field="name"
						:clearable="false"
						@select="onSelectEnd"
					/>
				</template>
			</view>
			
			<easy-picker :visible.sync="modelVisible" :list="selectOptions.models" value-field="code" label-field="name" @select="onChangeModel"></easy-picker>
		</view>
		<template v-slot:footer>
			<view class="bottom-btns-row">
				<view class="btn-frame"><u-button text="重 置" @click="onReset"></u-button></view>
				<view class="divider"></view>
				<view class="btn-frame"><u-button type="primary" text="提 交" @click="onSubmit"></u-button></view>
			</view>
		</template>
	</default-header-page-layout>
</template>

<script>
import DefaultHeaderPageLayout from '@/components/DefaultHeaderPageLayout.vue'
import ActionUserRow from '@/components/ActionUserRow.vue'
import ScanInputFormItem from '@/components/ScanInputFormItem.vue'
import EasySelectFormItem from '@/components/EasySelectFormItem.vue'
import EasyPicker from '@/components/EasyPicker.vue'
import { $alert, $successInfo, parseDic, getDicList, getUserDefaultLine } from '@/static/js/utils/index.js'
const defaultForm = {
	container:'',
	startCode:'',
	endCode:'',
	line:null
}
let initInterVal = null;
export default {
	name:'transportPage',
	components:{DefaultHeaderPageLayout,ActionUserRow,ScanInputFormItem,EasySelectFormItem,EasyPicker},
	data(){
		return {
			pageBodyHeight:0,
			form: {...defaultForm},
			msg:{
				container:'',
				startCode:'',
				endCode:'',
				line:''
			},
			selectOptions:{
				lines:[],
				starts:[],
				ends:[],
				models:[]
			},
			msgType:{
				container:'error'
			},
			container:null,
			selectContainer:'',
			modelVisible:false
		}
	},
	watch:{
		'form.line'(newVal,oldVal) {
			if (newVal!==oldVal) {
				this.watchLine()
			}
		}
	},
	methods:{
		onSearchContainer(){
			if (!this.form.container) {
				this.msgType.container = 'error'
			  this.msg.container = '请输入托盘码！';
			  return false;
			}
			this.msg.container = '';
			this.getContainerInfo()
		},
		onClearContainer(){
			this.clearContainer()
		},
		clearContainer(){
			this.form.container = ''
			this.msg.container = ''
			this.container = null
		},
		clearStations(){
			this.selectOptions.starts = []
			this.selectOptions.ends = []
			this.form.startCode = ''
			this.selectContainer = ''
			this.form.endCode = ''
			this.msg.startCode = ''
			this.msg.endCode = ''
		},
		reset(){
			this.clearContainer()
			this.form.line = null
			this.msg.line = ''
		},
		watchLine(){
			if (this.form.line) {
				this.changeFillLine()
			} else {
				this.clearStations()
			}
			this.msg.line = ''
		},
		onSelectStart(val,obj){
			this.msg.startCode = ''
			this.selectContainer = obj.containerCode
			this.getContainerInfoBySelectStation()
		},
		onSelectEnd(){
			this.msg.endCode = ''
		},
		getContainerInfoBySelectStation(){
			if (this.selectContainer) {
				this.getContainerInfo()
			} else {
				this.clearContainer()
			}
		},
		getContainerInfo(callback){
			const __setErrMessage = function(__msg) {
				if (!__msg) {
					__msg = '网络错误，请稍后再尝试！'
				}
				if (this.selectContainer) {
					$alert(__msg)
				} else {
					this.msgType.container = 'error'
					this.msg.container = __msg;
				}
			}.bind(this)
			let params = {}
			if (this.selectContainer) {
				params.ContainerCode = this.selectContainer
			} else {
				params.ContainerCode = this.form.container
			}
			this.$api.get('ContainerInformation',params,{block:'transport',fullRes:true,warn:false}).then((d)=>{
				if (d.data) {
					if (d.data.wmsContainer) {
						this.container = d.data.wmsContainer
						if (!this.selectContainer) {
							let _temp1 = parseDic(this.$store,'container_status',this.container.containerStatus)
							this.msgType.container = 'info'
							this.msg.container = `尺寸：${this.container.specLength}*${this.container.specWidth}，状态：${_temp1}`
						}
						callback && callback(true)
					} else {
						this.clearContainer()
						__setErrMessage(d.message)
						callback && callback(false)
					}
				} else {
					this.clearContainer()
					__setErrMessage(d.message)
					callback && callback(false)
				}
			}).catch((_errmsg)=>{
				this.clearContainer()
				__setErrMessage()
				callback && callback(false)
			})
		},
		changeFillLine(){
			uni.showLoading({
				title: '加载中...',
				mask:true
			});
			this.getStationsOptions((f)=>{
				if (f) {
					if (this.selectContainer) {
						this.getContainerInfo(()=>{
							uni.hideLoading();
						},false)
					} else {
						uni.hideLoading();
					}
				} else {
					uni.hideLoading();
				}
			})
		},
		getLinesOptions(){
			this.$api.get('SelectProductionline',{},{block:'transport'}).then(d=>{
				this.selectOptions.lines = d || []
				let val = getUserDefaultLine(this.$store,this.selectOptions.lines,'id')
				if (!val && this.selectOptions.lines.length===1) {
					val = this.selectOptions.lines[0].id
				}
				if (val) {
					this.form.line = val
				}
			}).catch(err=>{
				console.log(err)
			})
		},
		getStationsOptions(callback){
			this.$api.get('GetStartEndStation',{id:this.form.line},{block:'transport',loading:false}).then(d=>{
				this.selectOptions.starts = d.startList || []
				this.selectOptions.ends = d.endList || []
				if (this.selectOptions.starts.length===1) {
					this.form.startCode = this.selectOptions.starts[0].code
					this.selectContainer = this.selectOptions.starts[0].containerCode
				} else {
					this.form.startCode = ''
					this.selectContainer = ''
				}
				if (this.selectOptions.ends.length===1) {
					this.form.endCode = this.selectOptions.ends[0].code
				} else {
					this.form.endCode = ''
				}
				this.msg.startCode = ''
				this.msg.endCode = ''
				callback && callback(true)
			}).catch(err=>{
				this.clearStations()
				console.log(err)
				callback && callback(false)
			})
		},
		onReset(){
			this.reset()
		},
		onSubmit(){
			let check = this.checkBeforeSubmit()
			if (!check.flag) return false;
			this.modelVisible = true
		},
		onChangeModel(val){
			this.dealSubmit(val)
		},
		checkBeforeSubmit(){
			let res = {flag:true,data:this.form}
			if (!res.data.line) {
				this.msg.line = '请选择产线！'
				res.flag = false
			} else {
				this.msg.line = ''
			}
			if (res.flag && !res.data.startCode) {
				this.msg.startCode = '请选择起始位！'
				res.flag = false
			} else {
				this.msg.startCode = ''
			} 
			if (res.flag && !this.container) {
				const msgtext = '请先录入托盘信息！'
				if (!this.selectContainer) {
					this.msg.container = msgtext
					this.msgType.container = 'error'
				} else {
					$alert(msgtext)
				}
				res.flag = false
			} else {
				this.msg.startCode = ''
			} 
			if (res.flag && !res.data.endCode) {
				this.msg.endCode = '请选择目标位！'
				res.flag = false
			} else {
				this.msg.endCode = ''
			}
			return res;
		},
		dealSubmit(val){
			let params = {...this.form}
			params.container = this.container.containerCode
			params.assembleTask = val
			this.submiAjax(params,(f)=>{
				if (f) {
					$successInfo('提交成功')
					this.reset()
				}
			})
		},
		submiAjax(params,callback){
			this.$api.post('SubmitTransport',params,{block:'transport'}).then(()=>{
				callback && callback(true)
			}).catch((e)=>{
				callback && callback(false,e)
			})
		},
		/* 页面初始化获取页面body高度的定时器 */
		startInitInterval(callback){
			initInterVal = setInterval(()=>{
				if (this.pageBodyHeight) {
					this.clearInitInterval()
					callback && callback()
				} else {
					this.pageBodyHeight = this.$refs.page.getBodyHeight()
				}
			},200)
		},
		/* 清除定时器 */
		clearInitInterval(){
			try{
				clearInterval(initInterVal)
				initInterVal = null
			}catch(e){
				//TODO handle the exception
			}
		}
	},
	onReady(){
		this.startInitInterval(()=>{
			/* 页面初始化后需要执行的代码在这边调用 */
			this.getLinesOptions()
			this.selectOptions.models = getDicList(this.$store,'assemble_taskmodel')
		})
	},
	onUnload(){
		this.clearInitInterval()
	}
}
</script>

<style scoped lang="scss">
.forma-item{
	margin-bottom: 24rpx;
}
.bottom-btns-row{
	display: flex;
	padding: 10rpx 20rpx;
	background-color: #fff;
	.btn-frame{
		width: 1%;
		box-sizing: border-box;
		flex-grow: 1;
	}
	.divider{
		width: 20rpx;
		flex-shrink: 0;
	}
}
.only-watch-container{
	background-color: #D0DDD8;
	min-height: 90rpx;
	display: flex;
	&>.label{
		color: $u-tips-color;
		font-size: 32rpx;
		flex-shrink: 0;
		padding-left: 20rpx;
		padding-top: 22rpx;
	}
	&>.content{
		width: 1px;
		flex-grow: 1;
		display: flex;
		align-items: center;
		font-size: 30rpx;
		padding: 8rpx 0;
	}
}
</style>